# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
import math
import random
import time
import d_task
import d_items
import d_server

class Task:
    def __init__(self):
        # self.get_task();
        pass

    # 分配当天任务
    def get_task_daily(self):
        daily = []
        key = []
        for i in range(0,d_task.task["daily_total"]["value"],1):
            key.append(i)
        while len(daily) <= d_task.task["daily_count"]["value"]:
            j = random.randint(0, len(key) - 1)
            if d_task.task["daily_%d"%(key[j]+1)]["is_used"] == 0:
                continue
            daily.append({"id": key[j] + 1, "state": 0})
            del key[j]
        return daily

    # 重置活跃领奖数
    def refresh_daily_active(self):
        active = "0"
        for i in range(1,d_task.task["daily_active_award"]["value"],1):
            active = active + ",0"
        return active

    # 分配活跃任务
    def get_task_action(self):
        actions = []
        for i in range(0,d_task.task["action_enable"]["value"],1) :
            state = "0"
            action = d_task.task["action_%d"%(d_task.task["action_enable_%d"%(i)]["actionId"])]
            for j in range(1,action["stage"],1) :
                state = state + ",0"
            actions.append({"id": action["id"], "state": state})
        return actions

    # 获取角色任务数据
    def get_task(self):
        # 判断是否为同一天
        if int(time.time()/86400) != int(self.task_daily_time/86400) :
            self.task_daily_list = self.get_task_daily()
            self.task_daily_active = 0
            self.task_daily_active_gain = self.refresh_daily_active()
            self.task_daily_time = int(time.time())
        if len(self.task_action_list) == 0 :
            self.task_action_list = self.get_task_action()
            self.task_action_time = int(time.time())

    # 变更每日任务状态
    # mode 对应配置文件d_task中的 mode
    # count 为数量, 默认不传为1
    # extras 若为种植或收获任务,传种子的id ,若为获得某物品的任务,则为物品id
    def task_daily_update(self, mode, count=1, extras=0):
        # print("mode : " , mode)
        for daily in self.task_daily_list :
            cfg_daily = d_task.task["daily_%d"%(daily["id"])]
            #获得该模式的任务
            if cfg_daily["mode"] == mode :
                # 判断该任务是否已经完成
                print('daily["state"] : ',daily["state"])
                if daily["state"] < 0 :
                    continue
                # 根据不同附加条件进行条件判断
                if cfg_daily["condition"] == d_task.task["condition_quality"]["value"] :
                    if d_items.items[extras]["rate"] in cfg_daily["extras"]:
                        daily["state"] = daily["state"] + count
                elif cfg_daily["condition"] == d_task.task["condition_crop"]["value"] :
                    if extras in cfg_daily["extras"]:
                        daily["state"] = daily["state"] + count
                elif cfg_daily["condition"] == d_task.task["condition_prop"]["value"]:
                    if extras in cfg_daily["extras"]:
                        daily["state"] = daily["state"] + count
                else:
                    daily["state"] = daily["state"] + count
                # 判断任务是否已经完成
                if daily["state"] >= cfg_daily["count"]:
                    daily["state"] = d_task.task["state_complete"]["value"]
                self.task_daily_list = self.task_daily_list
        for action in self.task_action_list :
            cfg_action = d_task.task["action_%d"%(action["id"])]
            #获得该模式任务
            if cfg_action["mode"] == mode :
                if cfg_action["way"] == d_task.task["action_way_pile"]["value"] :    #累计模式活动
                    states = action["state"].split(",")
                    for i in range(0, len(states), 1) :
                        state = int(states[i])
                        if state < 0 :
                            continue
                        if cfg_action["condition"][i][0] == d_task.task["condition_quality"]["value"]:
                            if d_items.items[extras]["rate"] == cfg_action["extras"][i][0]:
                                state = state + count
                        elif cfg_action["condition"][i][0] == d_task.task["condition_crop"]["value"]:
                            if "%d"%(extras) == cfg_action["extras"][i][0]:
                                state = state + count
                        elif cfg_action["condition"][i][0] == d_task.task["condition_nothing"]["value"]:
                            state = state + count
                        if state >= int(cfg_action["count"][i][0]):
                            state = d_task.task["state_complete"]["value"]
                        states[i] = "%d"%(state)
                        break
                    action["state"] = ",".join(states)
                    self.task_action_list = self.task_action_list

    # 提交任务
    def taskCommit(self, mode, count=1, extras=0):
        self.task_daily_update(mode, count, extras)

    # 领取任务奖励
    def taskFinish(self, id, task_type, stage):
        if task_type == d_task.task["type_daily"]["value"] :     # 每日任务
            for daily in self.task_daily_list :
                if id == daily["id"] :
                    if daily["state"] != d_task.task["state_complete"]["value"] :
                        break
                    dailyCfg = d_task.task["daily_%d" % (id)]
                    for award_k, award_v in enumerate(dailyCfg["award"]) :
                        eval("self.task_gain_%s(%d,%d)"%(d_task.task[award_v]["value"],dailyCfg["reward"][award_k],dailyCfg["supply"][award_k]))
                    daily["state"] = d_task.task["state_finish"]["value"]
                    self.task_daily_update(d_task.task["mode_finish_task"]["value"])
                    self.task_daily_list = self.task_daily_list
                    break
        elif task_type == d_task.task["type_action"]["value"] :  #活动任务
            for action in self.task_action_list :
                if id == action["id"] :
                    states = action["state"].split(",")
                    if states[stage] != "%d"%(d_task.task["state_complete"]["value"]) :
                        break
                    for award_k, award_v in enumerate(d_task.task["action_%d"%(id)]["award"][stage]) :
                        eval("self.task_gain_%s(%d,%d)" % (
                        d_task.task[award_v]["value"], int(d_task.task["action_%d" % (id)]["reward"][stage][award_k]),
                        int(d_task.task["action_%d" % (id)]["supply"][stage][award_k])))
                    states[stage] = "%d"%(d_task.task["state_finish"]["value"])
                    action["state"] = ",".join(states)
                    self.task_action_list = self.task_action_list
                    break
        self.client.onTaskFinish(id, task_type, stage)

    # 获得活跃值
    def task_gain_award_active(self,reward,_=0) :
        self.task_daily_active = self.task_daily_active + reward

    # 获得积分
    def task_gain_award_integral(self,reward,_=0) :
        self.addScore(reward, d_server.ScoreType.Task)

    # 获得 (待完成)
    def task_gain_award_(self,reward,_=0) :
        print("task_gain_award_")
        pass

    # 获得道具
    def task_gain_award_prop(self,reward,id) :
        self.addItem(id, reward)
        pass

    # 获得转盘次数
    def task_gain_award_turntable(self, reward,_=0):
        self.addPhysicalValue(reward)
        pass

    # 领取每日活跃奖励
    def taskDailyActiveReceive(self,index):
        # 不同的奖励模式进行不同的操作
        active_gain = self.task_daily_active_gain.split(",")
        if active_gain[index] == "%d"%(d_task.task["state_finish"]["value"]) :
            return
        daily_active = d_task.task["daily_active_%d"%(index)]
        if daily_active["mode"] == d_task.task["award_mode_fixed"]["value"] :
            eval("self.task_gain_%s(%d)"%(d_task.task[daily_active["award"]]["value"],
                 daily_active["reward"][0]))
            pass
        elif daily_active["mode"] == d_task.task["award_mode_prop_fixed"]["value"] :
            eval("self.task_gain_%s(%d,%d)"%(d_task.task[daily_active["award"]]["value"] ,
                 daily_active["reward"][1],daily_active["reward"][0] ))
            pass
        elif daily_active["mode"] == d_task.task["award_mode_random"]["value"] :
            eval("self.task_gain_%s(%d)"%( d_task.task[daily_active["award"]]["value"] ,
                random.randint(daily_active["reward"][0],daily_active["reward"][1])))
            pass
        active_gain[index] = "%d"%(d_task.task["state_finish"]["value"])
        self.task_daily_active_gain = ",".join(active_gain)
        self.client.onTaskDailyActiveReceive(index)
        pass
